var ws = require('nodejs-websocket');
var clients = {
};

function publishStatusChanged(){
    let ntfdata = {
        data:status(),
        method:'statusChanged'
    }
    for(let k in clients){
       sendObject(clients[k].socket,ntfdata);
    }
}

function status(){
    let data=new Array();
    for(let i in clients){
        let element = clients[i]
        data.push({
            id:element.id,
            publish:element.publish
        })
    }
    return data;
}
function removeClient(socket){
    for(let i in clients){
        let element = clients[i]
        if(element.socket==socket)
        {
           delete clients[i];
           break;     
        }
    }
}
function getClientById(id){
    if(clients.hasOwnProperty(id))
        return clients[id];
    return null;
    
}

function getClient(socket){
    for (let key in clients) {
    　　var item = clients[key];
        if(item.socket==socket)
            return item;
    }
}
/*
{
}

*/
function sendObject(socket,obj){
    socket.sendText(JSON.stringify(obj));
}

function createChannel(client,cmd){
    let des = getClientById(cmd.id);
    if(des==null)
        return;
    sendObject(des.socket,{
        method:'createSenderNotify',
        data:{
            id:client.id
        }
    }); 
}
function receiverCandidate(client,cmd){
    let des = getClientById(cmd.id);
    if(des==null)
        return;
    sendObject(des.socket,{
        method:'senderCandidateNotify',
        data:{
            id:client.id,
            candidate:cmd.candidate
        }
    }); 
}
function senderCandidate(client,cmd){
    let des = getClientById(cmd.id);
    if(des==null)
        return;
    sendObject(des.socket,{
        method:'receiverCandidateNotify',
        data:{
            id:client.id,
            candidate:cmd.candidate
        }
    }); 
}
function offer(client,cmd){
    let des = getClientById(cmd.id);
    if(des==null)
        return;
    sendObject(des.socket,{
        method:'createReceiverNotify',
        data:{
            id:client.id,
            offer:cmd.offer
        }
    }); 
}
function answer(client,cmd){
    let des = getClientById(cmd.id);
    if(des==null)
        return;
    sendObject(des.socket,{
        method:'answer',
        data:{
            id:client.id,
            answer:cmd.answer
        }
    }); 
}



var server = ws.createServer(function(socket){
// 事件名称为text(读取字符串时，就叫做text)，读取客户端传来的字符串
　  var count = 1;
    socket.on('text', function(str) {
　　     // 在控制台输出前端传来的消息　　
        let cmd = JSON.parse(str);
        let client = null;
        if(cmd.method!="getStatus")
            client = getClient(socket);
        switch(cmd.method){
            case 'publish':
                if(!client.publish){
                    client.publish = true;
                    publishStatusChanged();


                    

                }
            case "getStatus":
                if(clients.hasOwnProperty(cmd.id)){
                    
                    sendObject(socket,{
                        data:status(),
                        method:'statusChanged'
                    });
                    
                }else{
                    clients[cmd.id]={
                        socket:socket,
                        id:cmd.id,
                        publish:false
                    }
                    publishStatusChanged();
                }
                break;
            case "createChannel":
                createChannel(client,cmd);
                break;
            case "receiverCandidate":
                receiverCandidate(client,cmd);
                break;
            case "senderCandidate":
                senderCandidate(client,cmd);
                break;
            case "offer":
                offer(client,cmd);
                break;
            case "answer":
                answer(client,cmd);
                break;
        }
        console.log(str);
        //向前端回复消息
        //socket.sendText('服务器端收到客户端端发来的消息了！' + count++);
    });
    socket.on('close',(code,reason)=>{
        console.log("close");
        removeClient(socket);
        console.log("client count " + Object.keys(clients).length);
    });
    socket.on('error',(error)=>{
        console.log("error");
        removeClient(socket);
        console.log("client count " + Object.keys(clients).length);
    });
}).listen(3000); 